import { useState, useEffect } from "react";
import styles from "./index.less";
import Tabbar from "@/components/Tabbar";
import HomeHeader from "./components/HomeHeader";
import api from "@/utils/api";
import { Swiper, Grid } from "antd-mobile";
import Items from "./components/Items";
import InfiniteScroll from "react-infinite-scroll-component";
import { useNavigate } from "umi";
export default function Page() {
  const navigate = useNavigate();
  // 首页轮播数据
  const [banners, setBanners] = useState<any[]>([]);
  const fetchBanners = () => {
    api.getHomeBanners().then((res) => {
      if (res.data.code === 0) {
        setBanners(res.data.data);
      }
    });
  };
  // 宫格导航分类数据处理
  const [cates, setCates] = useState<Cate[]>([]);
  const getCates = () => {
    api.getCates().then((res) => {
      if (res.data.code === 0) {
        setCates(res.data.data);
      }
    });
  };

  // 首页推荐商品的数据
  const [page, setPage] = useState(1);
  const [items, setItems] = useState<Item[]>([]);
  const getItems = () => {
    api
      .getItems({
        page,
        pageSize: 5,
      })
      .then((res) => {
        if (res.data.code === 0) {
          setItems([...items, ...res.data.data.result]);
        }
        if (res.data.code === 700) {
          setHasMore(false)
        }
      });
  };
  const reachBottom = () => {
    setPage(page+1);
  }
  const [hasMore, setHasMore] = useState(true);
  useEffect(() => {
    getItems();
  }, [page])
  useEffect(() => {
    fetchBanners();
    getCates();
    
  }, []);
  return (
    <>
      <HomeHeader />
      <div className={styles["home-container"]}>
        {/* 轮播 */}
        <Swiper autoplay loop>
          {banners.map((banner: any) => (
            <Swiper.Item key={banner.id}>
              <img src={banner.picUrl} />
            </Swiper.Item>
          ))}
        </Swiper>
        {/* /轮播 */}
        {/* 宫格导航 */}
        <Grid columns={4} gap={8}>
          {cates.map((cate: Cate) => (
            <Grid.Item key={cate.id}>
              <div className="grid-item" onClick={() => {
                navigate(`/itemLists/${cate.id}`)
              }}>
                <img src={cate.icon} className="icon" alt="" />
                <h5>{cate.name}</h5>
              </div>
            </Grid.Item>
          ))}
        </Grid>
        {/* /宫格导航 */}

        {/* 推进商品列表 */}
        <InfiniteScroll
          dataLength={items.length} //This is important field to render the next data
          next={reachBottom}
          hasMore={hasMore}
          loader={<h4 style={{textAlign: 'center'}}>加载中...</h4>}
          endMessage={
            <p style={{ textAlign: "center" }}>
              <b>---我也是有底线的---</b>
            </p>
          }
        >
          <Items items={items} />
        </InfiniteScroll>
        {/* /推荐商品列表 */}
      </div>
      <Tabbar />
    </>
  );
}
